<template>
	<view class="u-dropdown">
		<view class="u-dropdown__menu" :style="{
			height: uni.$utils.addUnit(height)
		}" :class="{
			'u-border-bottom': borderBottom
		}">
			<scroll-view class="scroll-view_H" :show-scrollbar="false" scroll-x="true">
				<view class="x-f" style="height: 100%;">
					<view class="u-dropdown__menu__item" v-for="(item, index) in menuList" :key="index"
						@tap.stop="menuClick(index)" :class="{ 'u-dropdown__menu__item--disabled': item.disabled }">
						<view class="u-flex u-flex-row items-center">
							<text class="u-dropdown__menu__item__text" :style="{
								color: item.disabled ? '#c0c4cc' : (isActive(index) ? activeColor : inactiveColor),
								fontSize: uni.$utils.addUnit(titleSize)
							}">{{ item.title }}</text>
							<view class="u-dropdown__menu__item__arrow" :class="{
								'u-dropdown__menu__item__arrow--rotate': isActive(index)
							}">
								<up-icon :custom-style="{display: 'flex'}" :name="menuIcon"
									:size="uni.$utils.addUnit(menuIconSize)"
									:color="item.disabled ? '#c0c4cc' : (isActive(index) ? activeColor : '#c0c4cc')"></up-icon>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<slot name="filter"></slot>
		</view>

		<view class="u-dropdown__content" :style="[contentStyle, {
				transition: `opacity ${duration / 1000}s ease`,
				top: uni.$utils.addUnit(height)
			}]" @tap="maskClick" @touchmove.stop.prevent>
			<view class="u-dropdown__content__popup" :style="[popupStyle]">
				<slot></slot>
			</view>
			<view class="u-dropdown__content__mask"></view>
		</view>
	</view>
</template>

<script setup lang="ts" name="m-dropdown">
	import { computed, onMounted, ref, watch, nextTick, getCurrentInstance } from 'vue';
	import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";

	const props = defineProps({
		// 激活态颜色
		activeColor: {
			type: String,
			default: '#2979ff'
		},
		// 未激活态颜色
		inactiveColor: {
			type: String,
			default: '#606266'
		},
		// 点击遮罩关闭
		closeOnClickMask: {
			type: Boolean,
			default: true
		},
		// 点击自身关闭
		closeOnClickSelf: {
			type: Boolean,
			default: true
		},
		// 过渡时间(ms)
		duration: {
			type: [Number, String],
			default: 300
		},
		// 菜单高度
		height: {
			type: [Number, String],
			default: 40
		},
		// 显示下边框
		borderBottom: {
			type: Boolean,
			default: false
		},
		// 标题字体大小
		titleSize: {
			type: [Number, String],
			default: 14
		},
		// 内容圆角
		borderRadius: {
			type: [Number, String],
			default: 0
		},
		// 菜单图标
		menuIcon: {
			type: String,
			default: 'arrow-down'
		},
		// 图标大小
		menuIconSize: {
			type: [Number, String],
			default: 14
		}
	});

	const emit = defineEmits(['close', 'open', 'update:modelValue']);

	// 子组件实例列表
	let children = ref<any[]>([]);
	// 菜单列表
	let menuList = ref<any[]>([]);



	// 当前激活索引
	let current = ref(-1);
	// 下拉内容样式
	let contentStyle = ref({
		zIndex: -1,
		opacity: 0,
		height: '0px'
	});
	// 内容高度
	let contentHeight = ref(0);
	// 是否激活状态
	const isActive = (index : number) => current.value === index;

	// 点击菜单
	const menuClick = (index : number) => {
		const item = menuList.value[index];
		if (item.disabled) return;

		// 点击当前激活项且允许关闭
		if (isActive(index) && props.closeOnClickSelf) {
			close();
			return;
		}

		open(index);
	};

	// 打开下拉菜单
	const open = (index : number) => {
		if (contentHeight.value < 1) getContentHeight();

		// 更新状态
		current.value = index;
		contentStyle.value = {
			zIndex: 100,
			opacity: 1,
			height: `${contentHeight.value}px`
		};

		// 激活对应子组件
		children.value.forEach((child, i) => {
			child.setActive(i === index);
		});

		emit('open', index, menuList.value[index]);
	};

	// 关闭下拉菜单
	const close = () => {
		emit('close', current.value);
		contentStyle.value.opacity = 0;

		// 动画结束后重置状态
		setTimeout(() => {
			contentStyle.value = {
				zIndex: -1,
				opacity: 0,
				height: '0px'
			};
			current.value = -1;
			// 重置所有子组件激活状态
			children.value.forEach(child => {
				child.setActive(false);
			});
		}, Number(props.duration));
	};

	// 点击遮罩
	const maskClick = () => {
		if (props.closeOnClickMask) close();
	};

	// 计算弹窗样式
	const popupStyle = computed(() => ({
		transform: current.value === -1 ? 'translateY(-100%)' : 'translateY(0)',
		transition: `transform ${Number(props.duration) / 1000}s ease`,
		borderRadius: `0 0 ${uni.$utils.addUnit(props.borderRadius)} ${uni.$utils.addUnit(props.borderRadius)}`,
		backgroundColor: '#fff'
	}));

	const instance = getCurrentInstance() as any;
	// 获取内容高度
	const getContentHeight = () => {
		const windowHeight = uni.$utils.getWindowInfo().windowHeight;


		const query = uni.createSelectorQuery().in(instance.proxy);
		query.select('.u-dropdown__menu').boundingClientRect((data : any) => {
			console.log(data.height);
		}).exec();


		uni.$utils.$uGetRect('.u-dropdown__menu').then((res : any) => {
			contentHeight.value = windowHeight - res.bottom;
		});
	};

	// 监听窗口尺寸变化重新计算高度
	const handleResize = () => {
		if (current.value !== -1) {
			getContentHeight();
		}
	};

	// 初始化
	onMounted(() => {
		getContentHeight();
		// 监听窗口 resize
		uni.$on('resize', handleResize);
	});

	// 清理监听
	onUnload(() => {
		uni.$off('resize', handleResize);
	});

	const updateData = (newValue : string) => {
		// 父组件自己修改数据
		menuList.value.push(newValue)
	};

	// 暴露给子组件的方法
	defineExpose({
		props,
		updateData,
		children,
		menuList,
		current,
		close,
		open
	});
</script>

<style scoped lang="scss">
	.scroll-view_H {
		flex: 1;
		height: 100%;
		white-space: nowrap; // 确保横向滚动
	}

	.u-dropdown {
		flex: 1;
		width: 100%;
		position: relative;

		&__menu {
			display: flex;
			justify-content: space-between;
			align-items: center;
			position: relative;
			z-index: 11;
			height: 100%;

			&__item {
				display: inline-flex;
				justify-content: center;
				align-items: center;
				padding: 0 20rpx;
				height: 100%;
				box-sizing: border-box;

				&--disabled {
					opacity: 0.6;
					cursor: not-allowed;
				}

				.u-flex-row {
					flex-direction: row;
					align-items: center;
				}

				&__text {
					font-size: 28rpx;
					padding: 0 5rpx;
				}

				&__arrow {
					margin-left: 6rpx;
					transition: transform 0.3s ease;
					display: flex;
					align-items: center;

					&--rotate {
						transform: rotate(180deg);
					}
				}
			}
		}

		&__content {
			position: absolute;
			z-index: 8;
			width: 100%;
			left: 0;
			bottom: 0;
			overflow: hidden;

			&__mask {
				position: absolute;
				z-index: 9;
				background: rgba(0, 0, 0, 0.3);
				width: 100%;
				left: 0;
				top: 0;
				bottom: 0;
				transition: opacity 0.3s ease;
			}

			&__popup {
				position: relative;
				z-index: 10;
				width: 100%;
			}
		}

		.u-border-bottom {
			border-bottom: 1px solid #eee;
		}
	}
</style>